<?php

namespace app\http\middleware;
use app\backstage\model\Admin;
class CheckLogin
{
    public function handle($request, \Closure $next)
    {
        
        $login_token = cookie('login_token');

        $login_url = config('template.root_path').'/login';
        //未登录跳转到登录页
        if(!$login_token){

            if($request->isAjax()){
                return json(['code'=>102,'msg'=>'请重新登录']);
            }


            // return redirect(config('template.root_path').'/login');


            echo <<<DDD
            <script>window.top.location.href="$login_url"</script>
DDD;
                        exit;
    
        }

        $row = Admin::where('login_token',$login_token)->find();

        //token失效
        if(!$row){
            if($request->isAjax()){
                return json(['code'=>102,'msg'=>'请重新登录']);
            }
            
            echo <<<DDD
            <script>window.top.location.href="$login_url"</script>
DDD;
                        exit;
            // return redirect(config('template.root_path').'/login');
        }

        $request->role_id = $row['role_id'];
        $request->admin_id = $row['id'];
        return $next($request);
    }
}
